<template>
  <div class="app-container-custom">
    <el-row :gutter="10">
      <fold :span="5" :xs="24" :show.sync='sideshow'>
        <el-card shadow="never">
          <org-tree ref="orgTree" modelType="'dept','community','floor','unit','room'" @nodeClick="handleNodeClick" @firstNodeClick="handleFirstNodeClick"/>
        </el-card>
      </fold>
      <el-col :span="sideshow ? 19 : 24" :xs="24">
        <el-card shadow="never">
              <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
                <el-form-item label="单据号" prop="costNo">
                  <el-input
                    v-model="queryParams.costNo"
                    placeholder="请输入单据号"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="收费项目" prop="chargeId">
                  <el-input
                    v-model="queryParams.chargeId"
                    placeholder="请输入收费项目"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <template v-if="toggleSearchStatus">
                  <el-form-item label="收费标准" prop="normId">
                    <el-input
                      v-model="queryParams.normId"
                      placeholder="请输入收费标准"
                      clearable
                      size="small"
                      @keyup.enter.native="handleQuery"
                    />
                  </el-form-item>
                  <el-form-item label="应收日期" prop="receivableTime">
                    <el-date-picker clearable size="small"
                      v-model="queryParams.receivableTime"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择应收日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="计费开始日期" prop="beginTime">
                    <el-date-picker clearable size="small"
                      v-model="queryParams.beginTime"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择计费开始日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="计费结束日期" prop="finishTime">
                    <el-date-picker clearable size="small"
                      v-model="queryParams.finishTime"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择计费结束日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="收全日期" prop="fullReceiptDate">
                    <el-date-picker clearable size="small"
                      v-model="queryParams.fullReceiptDate"
                      type="date"
                      value-format="yyyy-MM-dd"
                      placeholder="选择收全日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="状态" prop="status">
                    <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
                      <el-option
                        v-for="dict in statusOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                  </el-form-item>
                </template>
                <el-form-item>
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                  <a @click="()=>toggleSearchStatus = !toggleSearchStatus" style="margin-left: 8px;color: #40a9ff;">
                    {{ toggleSearchStatus ? '收起' : '展开' }}
                    <i :class="toggleSearchStatus ? 'el-icon-arrow-up':'el-icon-arrow-down'" />
                  </a>
                </el-form-item>
              </el-form>

              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['payfee:ruleCost:add']"
                  >新增</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['payfee:ruleCost:edit']"
                  >修改</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['payfee:ruleCost:remove']"
                  >删除</el-button>
                </el-col>
                <el-col :span="1.5">
                  <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                :loading="exportLoading"
                    @click="handleExport"
                    v-hasPermi="['payfee:ruleCost:export']"
                  >导出</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
              </el-row>

              <el-table v-loading="loading" :data="ruleCostList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="单据号" align="center" prop="costNo" width="150"/>
                <el-table-column label="房屋名称" align="center" width="180">
                  <template slot-scope="scope">
                    <span>{{scope.row.communityName}}-{{scope.row.roomName}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="客户" align="center" prop="ownerName" width="150"/>
                <el-table-column label="收费类型" align="center" prop="projectId" width="150" :formatter="projectFormat"/>
                <el-table-column label="收费项目" align="center" prop="chargeId" width="150" :formatter="itemFormat"/>
                <!--<el-table-column label="收费标准" align="center" prop="normNames" width="150" />-->
                <el-table-column label="应收日期" align="center" prop="receivableTime" width="180">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.receivableTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="计费开始日期" align="center" prop="beginTime" width="180">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="计费结束日期" align="center" prop="finishTime" width="180">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="金额" align="center" prop="moneys"  width="120"/>
                <el-table-column label="已收金额" align="center" prop="haveMoney"  width="120"/>
                <el-table-column label="状态" align="center" prop="status"  width="120" :formatter="statusFormat" />
                <el-table-column label="备注" align="center" prop="remark"  width="120" show-overflow-tooltip/>
                <el-table-column label="操作" align="center"  width="150" fixed="right" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['payfee:ruleCost:edit']"
                    >修改</el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['payfee:ruleCost:remove']"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
              />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改常规费用单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row :gutter="20">
 <!--   <el-col :span="8" :xs="24">
        <el-form-item label="单据号" prop="costNo">
          <el-input v-model="form.costNo" placeholder="请输入单据号" />
        </el-form-item>
    </el-col>-->
    <el-col :span="8" :xs="24">
        <el-form-item label="房屋" prop="roomId">
          <el-input v-model="form.roomName" class="input-with-select" readonly>
            <el-button slot="append" icon="el-icon-search" @click="() => this.$refs.roomRef.show()"></el-button>
          </el-input>
        </el-form-item>
    </el-col>
    <el-col :span="8" :xs="24">
        <el-form-item label="客户" prop="ownerId">
          <el-select v-model="form.ownerId">
            <el-option v-for="item in ownerOptions"
                       :key="item.id"
                       :label="item.ownerName"
                       :value="item.id"
            />
          </el-select>
        </el-form-item>
    </el-col>
    <el-col :span="8" :xs="24">
        <el-form-item label="收费类型" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择收费类型">
            <el-option v-for="item in projectOptions"
                       :key="item.projectId"
                       :label="item.projectType"
                       :value="item.projectId"
            />
          </el-select>
        </el-form-item>
    </el-col>
    <el-col :span="8" :xs="24">
        <el-form-item label="收费项目" prop="chargeId" placeholder="请选择收费项目">
          <el-select v-model="form.chargeId">
            <el-option v-for="item in itemOptions"
                       :key="item.chargeId"
                       :label="item.chargeName"
                       :value="item.chargeId"
            />
          </el-select>
        </el-form-item>
    </el-col>
    <el-col :span="8" :xs="24">
        <el-form-item label="应收日期" prop="receivableTime">
          <el-date-picker clearable size="small"
            v-model="form.receivableTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择应收日期">
          </el-date-picker>
        </el-form-item>
    </el-col>
    <el-col :span="8" :xs="24">
        <el-form-item label="计费开始日期" prop="beginTime">
          <el-date-picker clearable size="small"
            v-model="form.beginTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择计费开始日期">
          </el-date-picker>
        </el-form-item>
    </el-col>
    <el-col :span="8" :xs="24">
        <el-form-item label="计费结束日期" prop="finishTime">
          <el-date-picker clearable size="small"
            v-model="form.finishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择计费结束日期">
          </el-date-picker>
        </el-form-item>
    </el-col>
    <el-col :span="8" :xs="24">
        <el-form-item label="金额" prop="moneys">
          <el-input-number v-model="form.moneys" :precision="2" :step="10" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
    </el-col>
    <el-col :span="17" :xs="24">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
    </el-col>
          </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <TableSelect
      ref="roomRef"
      :listColumns="roomColumns"
      gridUrl="/property/room/list"
      @rowClick="roomSelect"
      dialogWidth="780px"
    />
  </div>
</template>

<script>
import { listRuleCost, getRuleCost, delRuleCost, addRuleCost, updateRuleCost, exportRuleCost,createRuleCost } from "@/api/payfee/ruleCost";
import { listItem } from "@/api/payfee/item";
import { listProject} from "@/api/payfee/project";
// import {listOwner} from "@/api/property/owner";
export default {
  name: "RuleCost",
  data() {
    return {
      toggleSearchStatus:false,
      sideshow:true,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 常规费用单表格数据
      ruleCostList: [],
      ownerOptions:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态字典
      statusOptions: [],

      proOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        costNo: null,
        roomId: null,
        deptId: null,
        ownerId: null,
        projectId: '03',
        chargeId: null,
        normId: null,
        roomNormId: null,
        receivableTime: null,
        beginTime: null,
        finishTime: null,
        prices: null,
        moneys: null,
        specialMoney: null,
        queenMoney: null,
        receivableMoney: null,
        haveMoney: null,
        costType: null,
        fullReceiptDate: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        roomId: [
          { required: true, message: "房屋不能为空", trigger: "blur" }
        ],
        ownerId: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "收费类型不能为空", trigger: "blur" }
        ],
        chargeId: [
          { required: true, message: "收费项目不能为空", trigger: "blur" }
        ],
      },
      currentNode:{},
      //收费项目字典
      itemOptions:[],
      //收费类型字典
      projectOptions:[],
      roomColumns:[
        {title:'楼栋',key:'floorName',type:'',isSearch:true},
        {title:'单元',key:'unitName',type:'',isSearch:true},
        {title:'房屋编号',key:'roomNum',type:'',isSearch:true},
        {title:'客户姓名',key:'ownerVo.ownerName',type:'',isSearch:true},
      ],
    };
  },
  created() {
    this.getList();
    this.getDicts("rule_cost_status").then(response => {
      this.statusOptions = response.data;
    });
    listItem({'projectId':'03'}).then(res=>{
      this.itemOptions = res.rows;
    })
    listProject({'projectCode':'03'}).then(res=>{
      this.projectOptions = res.rows;
    })

  },
  methods: {
    /** 查询常规费用单列表 */
    getList() {
      this.loading = true;
      listRuleCost(this.queryParams).then(response => {
        this.ruleCostList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getOwnerList(){
      listOwner().then(response => {
        this.ownerOptions =  response.rows;
      })
    },
    getProjectList(){
      listProject({'projectCode':'03'}).then(response => {
        this.proOptions = response.rows;
      })
    },
    getNowTime() {
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      var date = now.getDate(); //得到日期
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      var defaultDate = `${year}-${month}-${date}`;
      this.$set(this.form, "receivableTime", defaultDate);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 收费项目字典翻译
    itemFormat(row, column) {
      let index = this.itemOptions.findIndex(x=>x.chargeId == row.chargeId);
      if(index != -1){
        return this.itemOptions[index].chargeName
      }
      return '';
    },
    // 收费类型字典翻译
    projectFormat(row, column) {
      let index = this.projectOptions.findIndex(x=>x.projectId == row.projectId);
      if(index != -1){
        return this.projectOptions[index].projectType
      }
      return '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        costId: null,
        costNo: null,
        roomId: null,
        deptId: null,
        ownerId: null,
        projectId: null,
        chargeId: null,
        normId: null,
        roomNormId: null,
        receivableTime: null,
        beginTime: null,
        finishTime: null,
        prices: null,
        moneys: null,
        specialMoney: null,
        queenMoney: null,
        receivableMoney: null,
        haveMoney: null,
        costType: null,
        fullReceiptDate: null,
        status: '10001',
        ancestors: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        roomName:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.costId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加临时费用单";
      this.getOwnerList();
      this.getProjectList();
      this.getNowTime();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const costId = row.costId || this.ids
      getRuleCost(costId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改临时费用单";
        this.getOwnerList();
        this.getProjectList();
        this.getNowTime();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.costId != null) {
            updateRuleCost(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRuleCost(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const costIds = row.costId || this.ids;
      this.$confirm('是否确认删除临时费用单编号为"' + costIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRuleCost(costIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有临时费用单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportRuleCost(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    handleNodeClick(node){
      this.currentNode = node;
      this.queryParams.nodeId = node.id
      this.getList()
    },
    handleFirstNodeClick(node){
      this.currentNode = node;
      this.queryParams.nodeId = node.id;
      this.getList();
    },
    handleCreateRuleCost(){
      let param = {nodeId:this.currentNode.id,modelType:this.currentNode.modelType}
      this.$confirm(`是否创建组织为【${this.currentNode.label}】的费用单`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return createRuleCost(param);
      }).then(() => {
        this.getList();
        this.msgSuccess("费用创建成功");
      }).catch(() => {});
    },
    roomSelect(index,row){
      this.form.roomName=`${row.unitName}-${row.roomNum}`;
      this.form.roomId=row.id;
      this.form.ownerId=row.ownerId;
    },
  }
};
</script>
